<template>
  <div class="pnl upload-list">
    <div
      :class="['item', large ? 'large': '', isLoad ? 'height-150': '' ]"
      v-for="(item, index) in uploadList"
      :key="index"
    >
      <template v-if="item.status === 'finished'">
        <a v-if="item.imgUrl.indexOf('http') != -1 && upLoadType=='image'" @click="previewImg(item.imgUrl)">
          <img :src="item.imgUrl" />
        </a>
        <a class="file" v-if="item.imgUrl.indexOf('http') != -1 && (upLoadType=='file' || upLoadType== 'other' || upLoadType== 'typeSetting')">
          <Icon  class="file" type="ios-folder-outline" />
        </a>
        <a class="file" v-if="item.imgUrl.indexOf('http') != -1 && (upLoadType== 'media')">
          <Icon  class="file" type="md-videocam" />
        </a>
        <!-- <a v-else @click="previewImg(preFixPath + item.imgUrl)"><img :src="preFixPath + item.imgUrl "></a> -->
        <Icon class="btn-close" type="md-close-circle" @click.native="removeUploadItem(index)" v-if="!isClose"></Icon>
        <!-- <Icon v-if="maxlength > 1" :class="[maxlength > 1 ? 'btn-left' : '']" type="md-arrow-back" @click.native="leftUploadItem(index)"></Icon>
        <Icon v-if="maxlength > 1" :class="[maxlength > 1 ? 'btn-right' : '']" type="md-arrow-forward" @click.native="rightUploadItem(index)"></Icon> -->
        <div :title="item.name" class="name" v-if="(isLoad && (upLoadType=='file' || upLoadType== 'other' || upLoadType== 'typeSetting')) || isLoadChat">{{item.name}}</div>
        <Button v-if="isLoad && ai" type="text"  size="small" class="ml btn-load" @click="onload(item.imgUrl)">下载</Button>
      </template>
      <template v-show="item.status !== 'finished'">
        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
      </template>
    </div>
    <Upload
      class="item"
      ref="upload"
      :show-upload-list="false"
      :on-success="onUploadSuccess"
      :accept="accept"
      :format="format"
      :headers="headers"
      :max-size="uploadMax"
      :on-format-error="onUploadFormatError"
      :on-exceeded-size="onUploadSizeError"
      :disabled="disabled"
      type="drag"
      :action="url"
      v-show="uploadList.length < maxlength">
      <div v-if="this.upLoadType == 'image'">
        <Icon type="md-camera"></Icon>
      </div>
      <div v-else>
        <Icon type="ios-add" />
      </div>
    </Upload>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getOriginData,
  uploadImageUrl,
  uploadFlashUrl,
  uploadMediaUrl,
  uploadFileUrl,
  preFixPath} from "@/util";

export default {
  props: {
    ai: {
      type: Boolean,
      default: true
    },
    uploadList: {
      type: Array,
      default: []
    },
    maxlength: {
      type: Number,
      default: 5
    },
    upLoadType: {
      type: String,
      default: 'image'
    },
    large: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false
    },
    isLoad: {
      type: Boolean,
      default: false
    }, 
    isLoadChat: {
      type: Boolean,
      default: false
    },
    isClose: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      uploadImageUrl,
      uploadFlashUrl,
      uploadMediaUrl,
      uploadFileUrl,
      preFixPath,
      uploadMax: 1024 * 1024,
      headers: {}
    };
  },
  mounted() {
    let userToken = this.user.userToken
    if (userToken){
      this.headers['Access-Token'] = `${userToken}`;
    }
  },
  computed: {
    ...mapGetters(['user']),
    url() {
      let urlStr = ''
      switch (this.upLoadType) {
        case 'image':
          urlStr = this.uploadImageUrl
          break;
        case 'flash':
          urlStr = this.uploadFlashUrl
          break;
        case 'media':
          urlStr = this.uploadMediaUrl
          break;
        case 'typeSetting':
        case 'other':
        case 'file':
          urlStr = this.uploadFileUrl
          break;
      }
      return urlStr
    },
    accept() {
      let acceptStr = ''
      switch (this.upLoadType) {
        case 'image':
          acceptStr = ["jpg","jpeg","bmp","gif","png"].map(item => 'image/'+item).join(',');
          break;
        case 'flash':
          acceptStr = ["swf","flv"];
          break;
        case 'media':
          acceptStr = ["swf","flv","mp3","wav","avi","rm","rmvb","mp4"].map(item => 'video/'+item).join(',');
          break;
        case 'file':
          acceptStr = ["zip","rar","7z","doc","docx","xls","xlsx","ppt","pptx", "emf","prj","plt"].join(',');
          break;
        case 'other':
          acceptStr = "application/pdf,application/msword,application/vnd.ms-excel,application/vnd.ms-powerpoint"
          break;
        case 'typeSetting':
          acceptStr = "application/ms-nc"
      }
      return acceptStr
    },
    format() {
      let formatArr = '';
      switch (this.upLoadType) {
        case 'image':
          formatArr = ["jpg","jpeg","bmp","gif","png"];
          break;
        case 'flash':
          formatArr = ["swf","flv"];
          break;
        case 'media':
          formatArr = ["swf","flv","mp3","wav","avi","rm","rmvb","mp4"];
          break;
        case 'file':
          formatArr = ["zip","rar","7z","doc","docx","xls","xlsx","ppt","pptx", "emf","prj","plt"];
          break;
        case 'other':
          // formatArr = ["jpg","jpeg","bmp","gif","png"];
          formatArr = ["pdf","doc","xls","ppt"];
          break;
        case 'typeSetting':
          formatArr = ("nc,prj,pla,plt,boke,dgs,mkr,par,ctl,PLT,MRK,MDL,PLX,dxf,bpd,sff,pie").split(',')
        break;
      }
      return formatArr
    },
    imgWidth() {
      if(this.large) {
        return '_220w'
      }
      return '_110w'
    },
  },
  methods: {
    onload(imgsrc) {
      if (this.upLoadType == 'file' || this.upLoadType == 'typeSetting' || this.upLoadType == 'other' ) {
        window.location.href = imgsrc
        return
      }
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      image.src = imgsrc;
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function() {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
    
        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
    },
    removeUploadItem(i) {
      this.uploadList.splice(i, 1);
      this.uploadList.forEach((item, i) => {
        item.sort = i;
      });
      this.$emit("uploadPic", this.uploadList);
    },
    leftUploadItem(i) {
      let data = this.uploadList[i];
      this.uploadList.splice(i, 1);
      if (i == 0) {
        this.uploadList.splice(this.uploadList.length, 0, data);
      } else {
        this.uploadList.splice(i - 1, 0, data);
      }
      this.uploadList.forEach((item, i) => {
        item.sort = i;
      });
      this.$emit("uploadPic", this.uploadList);
    },
    rightUploadItem(i) {
      let data = this.uploadList[i];
      this.uploadList.splice(i, 1);
      if (i == this.uploadList.length) {
        this.uploadList.splice(0, 0, data);
      } else {
        this.uploadList.splice(i + 1, 0, data);
      }
      this.uploadList.forEach((item, i) => {
        item.sort = i;
      });
      this.$emit("uploadPic", this.uploadList);
    },
    onUploadSuccess(res, file) {
      if (res.code === 200) {
        file.url = res.data;
        let path = res.data;
        file.imgUrl = path;
        this.$Message.success("上传成功");
        this.uploadList.push(file);
      } else {
        this.$Notice.error({
          title: "上传失败",
          desc: res.message
        });
        this.$refs.upload.fileList.splice(this.$refs.upload.fileList.length - 1, 1);
      }
      this.uploadList.forEach((item, i) => {
        item.sort = i;
      });
      this.$emit("uploadPic", this.uploadList);
    },
    onUploadFormatError(file) {
      let text = 'jpg 或 png 格式的图片'
      if (this.upLoadType == 'typeSetting') {
        text = 'nc,prj,pla,plt,boke,dgs,mlr,par,ctl,PLT,MRK,MDL,PLX,dxf,bpd,sff,pie的文件'
      }
      this.$Notice.warning({
        title: "文件格式不正确",
        desc:
          "文件 " + file.name + `格式不正确，请上传${text} 。`
      });
      this.$emit("uploadPic", this.uploadList);
    },
    onUploadSizeError(file) {
      this.$Notice.warning({
        title: "超出文件大小限制",
        desc: "文件 " + file.name + " 太大，不能超过 "+parseInt(this.uploadMax/1024)+"M。"
      });
      this.$emit("uploadPic", this.uploadList);
    },
    previewImg (url) {
      this.$vueImgPreview(url)
    }
  }
};
</script>
